/**
 *
 */
package com.wedroid.api.web.controller;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.demo2do.core.support.Page;
import com.demo2do.core.support.Result;
import com.demo2do.core.utils.JsonUtils;
import com.wedroid.api.handler.HashidsDecoder;
import com.wedroid.api.handler.ResourceHandler;
import com.wedroid.api.mapper.MessageMapper;
import com.wedroid.api.service.ContacterService;
import com.wedroid.api.service.MessageService;
import com.wedroid.entity.contact.Contacter;

/**
 * @author lute
 */
@Controller
@RequestMapping("")
public class MessageController {

    @Autowired
    private HashidsDecoder decoder;

    @Autowired
    private ResourceHandler resourceHandler;

    @Autowired
    private ContacterService contacterService;

    @Autowired
    private MessageService messageService;

    /**
     * @param hashid
     * @param page
     * @return
     */
    @ResponseBody
    @RequestMapping("/contacters/{hashid}/messages")
    public String listMessages(@PathVariable("hashid") String hashid, Page page) {

        Result result = new Result();

        Optional<Long> decodedId = decoder.decode(hashid);
        if (decodedId.isPresent()) {

            Long id = decodedId.get();
            Contacter contacter = contacterService.load(id);

            List<MessageMapper> messages =
                    messageService.listMessages(contacter, page)
                                  .stream()
                                  .map(MessageMapper::new)
                                  .map(item -> item.resolveUrl(resourceHandler))
                                  .collect(Collectors.toList());

            result.success().data("messages", messages)
                            .data("page", page);
        } else {
            result.fail().message("INVALID_INDENTIFIER");
        }

        return JsonUtils.toJsonString(result);
    }

    /**
     * @param hashid
     * @return
     */
    @ResponseBody
    @RequestMapping("/contacters/{hashid}/messages/count")
    public String countMessages(@PathVariable("hashid") String hashid) {

        Result result = new Result();

        Optional<Long> decodedId = decoder.decode(hashid);
        if (decodedId.isPresent()) {

            Long id = decodedId.get();
            Contacter contacter = contacterService.load(id);

            int count = messageService.countMessages(contacter);
            result.success().data("count", count);
        } else {
            result.fail().message("INVALID_INDENTIFIER");
        }

        return JsonUtils.toJsonString(result);
    }


}
